package cc.siyecao.uid.redis.resposity;

import cc.siyecao.uid.core.exception.UidGenerateException;
import cc.siyecao.uid.core.resposity.WorkerNodeEntity;
import cc.siyecao.uid.core.resposity.WorkerNodeResposity;
import org.springframework.data.redis.core.RedisTemplate;

public class WorkerNodeRedis implements WorkerNodeResposity {
    private final RedisTemplate<String, Integer> redisTemplate;
    public String assigner = "fsg:uid:assigner";
    public String worker = "fsg:uid:worker";

    public void setAssigner(String assigner) {
        this.assigner = assigner;
    }

    public void setWorker(String worker) {
        this.worker = worker;
    }

    public WorkerNodeRedis(RedisTemplate<String, Integer> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public WorkerNodeEntity getWorkerNodeByHostPort(String host, String port) {
        return null;
    }

    @Override
    public void addWorkerNode(WorkerNodeEntity entity) {
        String workerKey = getWorkerKey( entity );
        Integer workerId = redisTemplate.opsForValue().get( workerKey );
        if (workerId != null && workerId != 0) {
            entity.setId( workerId );
        }
        Long incr = redisTemplate.opsForValue().increment( assigner );
        if (incr == null) throw new UidGenerateException();
        int value = incr.intValue();
        redisTemplate.opsForValue().set( workerKey, value );
        entity.setId( value );
    }

    private String getWorkerKey(WorkerNodeEntity entity) {
        return worker + entity.getHostName() + "_" + entity.getPort();
    }

}
